<script setup lang="ts">
import InstallationInformation from '@/pages/index/bindingBeeper/component/InstallationInformation.vue';
import EquipRequest from '@/request/equipRequest';
import useModal from '@/hooks/useModal';
import { navigate } from '@/utils/navigate';
import to from '@/utils/to';
import { useAppStore } from '@/store';
import useToast from '@/hooks/useToast';
import ReceivingAddressInfo from '@/pages/index/bindingBeeper/component/ReceivingAddressInfo.vue';

interface IState {
  beeperCode: string;
  bindCallerInfo?: IObtBindCallerInfoRes;
  hasAddressVisible: boolean;
  residentAddress: string;
}

const { showModal } = useModal();
const { showToast } = useToast();
const state = reactive<IState>({ beeperCode: '', hasAddressVisible: false, residentAddress: '' });
const store = useAppStore();

onLoad(async (options) => {
  if (!options || (!options.scene && !options.beeperCode)) {
    await showModal('呼叫器没有序列码，请联系客服');
    navigate({ url: '/pages/home/index', type: 'switchTab' });
    return;
  }
  if (options.beeperCode) {
    state.beeperCode = options.beeperCode;
  } else {
    const scene = decodeURIComponent(options.scene);
    state.beeperCode = scene.split('hc=')[1];
  }
  if (!useAppStore().$state.token) return;
  await fetchObtBindCallerInfo(state.beeperCode);
});

// 获得要绑定的呼叫器信息
const fetchObtBindCallerInfo = async (code: string) => {
  const [err, res] = await to(EquipRequest.ObtBindCallerInfo({ code, hasLoading: true }));
  if (err) {
    navigate({ url: '/pages/home/index', type: 'switchTab' });
    return;
  }
  state.bindCallerInfo = res.data;
  const { beeperBinding, addressType, requireAddress, villageName, buildName, unitName, floorName, houseNumber } = res.data;
  // 已经绑定此呼叫器
  if (beeperBinding && res.data.equipType === 1) {
    store.$patch({ beeperId: res.data.relationId });
    showToast('已经绑定过此呼叫器').then(() => {
      setTimeout(() => {
        navigate({ url: '/pages/home/index', type: 'switchTab' });
      }, 1000);
    });
    return;
  }
  // 呼叫器主用户是否依旧存在
  if (res.data.main) {
    // 用户下单时绑定地址 呼叫器绑定无需做操作，直接绑定
    if (requireAddress === 2) {
      await handleBindBeeper(res.data);
      return;
    }
    // 地址类型是1.呼叫器地址和联系人或者3.符合条件的就近收货地址或者requireAddress等于2(等于2表示呼叫器下单时绑定)的时候直接绑定
    if (addressType == 1 || addressType == 3) {
      // 直接绑定
      await handleBindBeeper(res.data);
      return;
    } else {
      // 2.呼叫器地址和下单联系人 4.呼叫器地址和门牌号 6.呼叫器地址和层、门牌号 7.呼叫器地址和单元、层、门牌号 8.呼叫器地址和栋、单元、层、门牌号 情况
      state.residentAddress = villageName || '';
      switch (addressType) {
        case 2: // 呼叫器地址和下单联系人
          state.residentAddress = state.residentAddress + (buildName || '') + (unitName || '') + (floorName || '') + (houseNumber || '');
          break;
        case 4: // 呼叫器地址和门牌号
          state.residentAddress = state.residentAddress + (buildName || '') + (unitName || '') + (floorName || '');
          break;
        case 6: // 呼叫器地址和层
          state.residentAddress = state.residentAddress + (buildName || '') + (unitName || '');
          break;
        case 7: // 呼叫器地址和单元、层、门牌号
          state.residentAddress = state.residentAddress + (buildName || '');
          break;
      }
      // 是否显示收货地址信息
      if ([2, 4, 5, 6, 7, 8].some((item) => addressType === item)) {
        state.hasAddressVisible = true;
      }
    }
  } else {
    if (addressType !== 1 && addressType !== 5) {
      state.residentAddress = (villageName || '') + (buildName || '') + (unitName || '') + (floorName || '') + (houseNumber || '');
    }
  }
};

// 直接绑定呼叫器
const handleBindBeeper = async (data: IObtBindCallerInfoRes) => {
  const [err] = await to(EquipRequest.BindCallerDevice({ equipId: data.equipId, hasLoading: true }));
  if (err) return;
  if (data.beeperType === 1) store.$patch({ beeperId: data.relationId });
  showToast('绑定呼叫器成功', 'success').then(() => {
    setTimeout(() => {
      navigate({ url: '/pages/home/index', type: 'switchTab' });
    }, 1000);
  });
};
</script>

<template>
  <view class="h-screen bg-white" v-if="!useAppStore().$state.token && state.beeperCode">
    <NotLogged :path="`/pages/index/bindingBeeper/index?beeperCode=${state.beeperCode}`" />
  </view>
  <view class="c-pd" v-else>
    <view class="bg-white c-br c-pd mb-12px flex justify-between items-center" v-if="state.residentAddress">
      <image src="https://pic.kanglailab.com/common/beeper.png" class="w-30px h-30px" mode="widthFix" />
      <view class="flex-1 ml-12px fw-bold">{{ state.residentAddress }}</view>
    </view>

    <!--  安装信息  -->
    <InstallationInformation v-if="state.bindCallerInfo && !state.bindCallerInfo.main" :beeperCode="state.beeperCode" :bindCallerInfo="state.bindCallerInfo" />
    <!--  收货地址信息  -->
    <ReceivingAddressInfo v-if="state.bindCallerInfo && state.hasAddressVisible" :beeperCode="state.beeperCode" :bindCallerInfo="state.bindCallerInfo" />
  </view>
</template>

<style lang="scss" scoped>
:deep(.van-cell__title) {
  margin-right: 12px !important;
  min-width: 72px !important;
  max-width: 72px !important;
}
</style>
